# -*- coding: utf-8 -*-
"""
@Time ： 2022/12/30 22:15
@Author ： PJC
"""
import sys
from typing import Optional

import requests
import json
import allure
from urllib.parse import urlencode
import time

from common.logger import *
from common.read_yaml import get_yaml
from common.read_config import env
from common.read_config import Environ
from common.route import login

# sys.path.append("")


# data = ReadYamlConfigs("data.yaml").get_yaml_data()#读取数据
data = get_yaml(Environ=Environ)


# print(data)


# print(data)


# print(data)


class HttpClient:
    def __init__(self):
        self.host = data['admin_host']
        # print(self.host)

    default_header = {
        "Content-Type": "application/json"
    }

    def send(self, url, body: Optional[dict] = None, method: Optional[str] = None, headers: Optional[dict] = None,
             sessions='',
             x_token=''):
        if not headers:
            headers = self.default_header
        # s = requests.Session()
        if x_token:
            # headers["Authorization"] = "Bearer " + x_token.strip('"')  # strip() 方法用于移除字符串头尾指定的字符（默认为空格或换行符）或字符序列。
            headers["Authorization"] = x_token.strip('"')  # strip() 方法用于移除字符串头尾指定的字符（默认为空格或换行符）或字符序列。
            print(headers)
        if sessions:
            # headers["Session"] = "Bearer " + sessions
            headers["Session"] = sessions

        if method == "get":
            result = requests.get(url, params=body, headers=headers)
            # result = s.get(url, params=body, headers=headers)
        elif method == "post":
            # result =  requests.post(url,data = json.dumps(body),headers=headers)
            result = requests.post(url, json=body, headers=headers)
            # result = s.post(url, json=body, headers=headers)
        elif method == "patch":
            result = requests.patch(url, data=json.dumps(body), headers=headers)
            # result = s.patch(url, data=json.dumps(body), headers=headers)

        # self.create_response_log(result.status_code, result.json())
        # self.create_request_log(url, method, body, headers)
        # assert result.status_code == 200
        return result.json()

    def get_full_url(self, url, etc={}, replace={}, h=""):
        if h:
            host = h.rstrip('/')  # rstrip() 删除 string 字符串末尾的指定字符（默认为空格）.
        else:
            host = self.host.rstrip('/')

        url = url.lstrip('/')  # lstrip() 方法用于截掉字符串左边的空格或指定字符。
        full_url = host + "/" + url
        # full_url += "?platform={}&time=".format(env) + str(int(round(time.time() * 1000)))
        if etc:
            s = urlencode(etc)  # urlencode  urllib库里面有个urlencode函数，可以把key-value这样的键值对转换成我们想要的格式，返回的是a=1&b=2这样的字符串
            full_url += "&" + s
        if replace:
            full_url = str.format(full_url,
                                  replace)  # str.format() 方法通过字符串中的花括号 {} 来识别替换字段 replacement field，从而完成字符串的格式化。
        return full_url

    @allure.step("请求日志")
    def create_request_log(self, url, method, body, headers):
        pass

    # print("请求日志",url,method,body,headers)
    @allure.step('响应日志')
    def create_response_log(self, status_code, text):
        # pass'
        print("响应日志", status_code, text)


if __name__ == '__main__':
    clent = HttpClient()
    # re = clent.send(
    #     url='http://www.kuaidi100.com/query',
    #     body={"type": "shentong", "postid": "773198225556081"}, method='get',
    #     headers={'Content-Type': 'application/json'})
    # print(re['data'])

    # res = clent.send(
    #     url='http://47.109.25.94:8080/ssm_web/user/login',
    #     body={'phone': '15281473522', 'password': '123456'},
    #     method='post')
    # a = res.json()
    # token = a['content']['access_token']
    # print(token)
    from common.read_config import lisi_token

    b = clent.send('http://47.109.25.94:8080/ssm_web/user/findAllUserByPage',
                   body={'currentPage': '5', 'pageSize': '5'},
                   method='post',
                   x_token=lisi_token)
    print(b)
    # header = {'Content-Type': 'application/json', 'Authorization': '1e283f29-694a-4335-bc56-c1ae903f0fcc'}
    # header['Authorization'] = token
    # print(header)
    # body = {'currentPage': '1', 'pageSize': '5'}
    # resu = requests.post('http://47.109.25.94:8080/ssm_web/user/findAllUserByPage', headers=header, json=body)
    # print(resu.json())
    # print(res['content']['access_token'])
    # data = {'phone': '15281473522', 'password': '123456'}
    # res = requests.post('http://47.109.25.94:8080/ssm_web/user/login', params=data)
    # print(res.json())
    # url = "https://openapi.vmall.com/rms/comment/getCommentList.json?"
    # body = {"pid": 10086198945779,
    #         "gbomCode": "",
    #         "type": 0,
    #         "extraType": 1,
    #         "pageSize": 10,
    #         "pageNum": 6}
    # res = requests.post(url, params=body, headers={'Content-Type': 'application/json'})
    # print(res.json())
    # print(requests.get(url='http://www.kuaidi100.com/query',
    #                    params={"type": "shentong", "postid": "773198225556081"}, ).json())

    # data0 = login['case_data'][0]['body']
    #
    # etc = {
    #     "username": 'username'
    #     , "password": 'password'
    # }
    #
    # url = login['url']
    # print(url)
    # method = login['method']
    # url = clent.get_full_url(login['url'], etc=etc, replace="")
    # print(url)
